package com.scy.face.config;

import com.arcsoft.face.FaceEngine;
import com.arcsoft.face.FaceFeature;
import com.arcsoft.face.FaceSimilar;
import com.scy.face.model.User;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author WH
 */
public class UserLibrary {

    private static List<User> users = new ArrayList<>();

    public static List<User> getUsers(){
        return users;
    }

    public static User loginByUP(String username, String password) {
        if (users.size() == 0) {
            return null;
        }
        List<User> temp = users.stream().filter(t -> t.getUsername().equals(username)).collect(Collectors.toList());
        if (temp == null || temp.size() != 1) {
            return null;
        }
        return temp.get(0).getPassword().equals(password) ? temp.get(0) : null;
    }

    public static User loginByFace(final byte[] bytes,FaceEngine faceEngine) {
        if (users.size() == 0) {
            return null;
        }
        int maxIndex = -1;
        float max = -1;
        for(int i =0;i<users.size();i++){
            FaceFeature targetFaceFeature = new FaceFeature();
            targetFaceFeature.setFeatureData(users.get(i).getFeatureData());
            FaceFeature sourceFaceFeature = new FaceFeature();
            sourceFaceFeature.setFeatureData(bytes);
            FaceSimilar faceSimilar = new FaceSimilar();
            faceEngine.compareFaceFeature(targetFaceFeature, sourceFaceFeature, faceSimilar);
            System.out.println("该图片与"+users.get(i).getUsername()+"的相似度为："+faceSimilar.getScore());
            if(faceSimilar.getScore() > max){
                max = faceSimilar.getScore();
                maxIndex = i;
            }
        }
        if(maxIndex != -1 && max > 0.85F){
            return users.get(maxIndex);
        }
        return null;
    }

    public static boolean add(User user) {
        if(!validate(user.getUsername())){
            return false;
        }
        users.add(user);
        return true;
    }

    private static boolean validate(String username) {
        if (users.size() == 0) {
            return true;
        }
        List<User> temp = users.stream().filter(t -> t.getUsername().equals(username)).collect(Collectors.toList());
        if (temp == null || temp.size() == 0) {
            return true;
        }
        return false;
    }
}
